// Package middleware
// @File: requestLogger.go
// @Description: 请求日志中间件
// @Author: YaoRuiQi
// @Date: 2025/8/23 02:51

package middleware

import (
	"GinStandardTemplate/internal/pkg/contextUtils"
	"GinStandardTemplate/utils/logger"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// getRequestIp
//
//	@Description: 获取请求的ip
//	@param header 请求头
//	@return string 获取到的ip
func getRequestIp(header *http.Header) string {
	if xRealIp := header.Get("X-Real-Ip"); xRealIp != "" {
		return xRealIp
	} else if xForwardedFor := header.Get("X-Forwarded-For"); xForwardedFor != "" {
		return xForwardedFor
	} else {
		return ""
	}
}

// GinLogger
//
//	@Description: 请求日志中间件
//	@param logger 日志记录器
//	@return gin.HandlerFunc
func GinLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		ctx, _ := contextUtils.FromContext(c.Request.Context())

		reqLogger := logger.NewLoggerWith(logger.Logger, ctx.RequestID, ctx.UserData)

		// 更新请求的上下文，增加日志记录器
		c.Request = c.Request.WithContext(contextUtils.NewRequestContext(
			c.Request.Context(), &contextUtils.RequestContext{
				RequestID: ctx.RequestID,
				Localizer: ctx.Localizer,
				UserData:  ctx.UserData,
				Logger:    reqLogger,
			},
		))

		c.Next()

		reqLogger.Info("requestMiddleware",
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", c.Request.URL.Path),
			zap.Duration("cost", time.Since(start)),
			zap.String("ip", getRequestIp(&c.Request.Header)),
		)
	}
}
